<template>
  <!--  服务管理  -->
  <div class="dictMapping app-container">
    <el-row :gutter="20" class="full-row">
      <!--左侧数据-->
      <div class="full-height" style="padding: 20px; overflow: auto">
        <el-input v-model="filterText" placeholder="输入关键字进行过滤" prefix-icon="el-icon-search" clearable @keyup.enter.native="handleFilter(filterText)" @clear="handleFilter(filterText)" />
        <div class="head-container" style="flex: 1; overflow: auto">
          <div class="title hk-flex">
            <div class="tit-left" @click="handleFilterAll">
              <span>服务目录</span>
            </div>
            <el-button
              type="text"
              icon="el-icon-circle-plus"
              @click.stop="() => append()"
            />
          </div>
          <el-tree
            v-show="showchild"
            ref="tree"
            :expand-on-click-node="false"
            default-expand-all
            :data="deptOptions"
            :props="defaultProps"
            current-node-key="1"
            :filter-node-method="filterNode"
            node-key="id"
            :highlight-current="isHightlight"
            @node-click="handleNodeClick"
          >
            <span slot-scope="{ node, data }" style="width: 90%; display: flex">
              <span v-if="!data.showInput" class="custom-tree-node">
                <span style="display:inline-block;width:calc(100% - 62px);overflow:hidden;text-overflow:ellipsis;" :title="data.label">{{ data.label }}</span>
                <i>
                  <el-button
                    type="text"
                    size="mini"
                    icon="el-icon-plus"
                    @click.stop="() => append(node, data)"
                  />
                  <el-button
                    type="text"
                    size="mini"
                    icon="el-icon-edit"
                    @click.stop="() => editNode(node, data)"
                  />
                  <el-button
                    type="text"
                    size="mini"
                    icon="el-icon-delete"
                    @click.stop="() => delNode(node, data)"
                  />
                </i>
              </span>
              <span v-else class="custom-tree-node">
                <el-input
                  v-model="data.label"
                  placeholder="不能为空"
                  size="mini"
                  maxlength="10"
                  class="innerput"
                />
                <i>
                  <el-button
                    type="text"
                    size="mini"
                    @click.stop="() => sureNode(node, data)"
                  >
                    确定
                  </el-button>

                  <el-button
                    type="text"
                    size="mini"
                    @click.stop="() => remove(node, data)"
                  >
                    取消
                  </el-button>
                </i>
              </span>
            </span>
          </el-tree>
        </div>
      </div>
      <!-- 表格  -->
      <div class="user">
        <HkSearchform
          :data="queryParams"
          :field-list="filterInfo.fieldList"
          @handleSearch="handleQuery"
          @handleReset="resetQuery"
        />
        <el-row :gutter="10" class="mt2">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
            >新增
            </el-button>
            <el-button
              size="mini"
              :disabled="ids.length == 0"
              @click="handleDel"
            >删除
            </el-button>
            <el-button size="mini" @click="handleImport">导入 </el-button>
            <el-button size="mini" :disabled="ids.length == 0" @click="handleExport">导出 </el-button>
          </el-col>
        </el-row>
        <HkTable
          style="flex: 1; overflow: auto"
          :loading="loading"
          :table-data="tableData"
          :table-columns="tableList"
          :selection="true"
          :operate="true"
          :total="total"
          :show-index="true"
          :select-fn="selectFn"
          table-height="80"
          :query-params="queryParams"
          show-overflow-tooltip
          @handleSelectionChange="handleSelectionChange"
          @changePage="getListData"
        >
          <template #operate="scope">
            <el-button
              v-if="!scope.row.isSystem"
              size="mini"
              type="text"
              @click="handleEdit(scope.row)"
            >编辑
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleSet(scope.row)"
            >设定优先级</el-button>
          </template>
          <template #enable="{ row }">
            <el-switch v-model="row.enable" @change="handleChangeEnable(row)" />
          </template>
          <template #type="{ row }">
            <span>{{ row.type==1?'事件管理':row.type==2?'问题管理':row.type==3?'变更管理':row.type==4?'部署与发布管理':'' }}</span>
          </template>
          <template #catalogueList="{ row }">
            {{ row.catalogueList.join("/") }}
          </template>
        </HkTable>
      </div>
    </el-row>
    <add-drawer ref="addDrawerRef" @handleSubmit="getListData" />
    <import-dialog ref="importDialogRef" :upload="uploadParams" @handleSubmit="getListData" />
  </div>
</template>

<script>
import {
  listTreeCatalogue,
  updateCatalogue,
  createCatalogue,
  deleteByIdCatalogue,
  pageList,
  deleteServiceDef,
  updateEnable
} from '@/api/basicConfig/serviceConfig'
import HkTable from '@/components/HkTable/index'
import HkSearchform from '@/components/HkSearchform/index.vue'
import addDrawer from './addDrawer'
import { gDownload } from '@/utils/request'
import importDialog from './importDialog.vue'
import { getToken } from '@/utils/auth'

export default {
  name: 'ServiceConfig',
  components: {
    HkTable,
    HkSearchform,
    addDrawer,
    importDialog
  },
  beforeRouteLeave(to, from, next) {
    from.meta.keepAlive = false
    next()
  },
  data() {
    return {
      // 是否显示搜索条件
      showchild: true,
      // 是否是添加状态
      appendState: false,
      // 字典维护所需要的
      upholdId: '',
      dictCode: '',
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      // 总条数
      total: 0,
      // 部门列表
      deptOptions: [],
      // 表格数据
      tableData: [],
      // 弹出层标题
      title: '',
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        catalogueId: null
      },
      // 搜索项配置
      filterInfo: {
        fieldList: [{ label: '服务名称', type: 'input', field: 'name' }]
      },
      //  表格
      tableList: [
        { label: '名称', param: 'name' },
        { label: '状态', param: 'enable', type: 'slot' },
        { label: '服务类型', param: 'type', type: 'slot' },
        { label: '流程', param: 'flowName' },
        { label: '服务目录', param: 'catalogueList', type: 'slot' },
        { label: '通知名称', param: 'noticeName' },
        { label: '负责人', param: 'userName' },
        { label: '描述', param: 'description' }
      ],
      defaultProps: {
        children: 'children',
        label: 'label'
      },

      // 表单校验
      rules: {},
      filterText: '',
      uploadParams: {
        headers: { Authorization: 'Bearer ' + getToken() },
        params: 'file',
        accept: '.xlsx',
        limit: undefined,
        url: window.baseUrl.ticket + '/serviceDef/import',
        fileList: []
      },
      isHightlight: false
    }
  },
  created() {
    this.getTreeselect()
    this.handleQuery()
  },
  methods: {
    handleFilter(val) {
      this.$refs.tree.filter(val)
    },
    // 点击服务目录查询全部
    handleFilterAll() {
      this.isHightlight = false
      this.queryParams.catalogueId = null
      this.getListData()
    },
    // 增加节点
    append(node, val) {
      this.appendState = true
      const newChild = { label: '', children: [] }
      newChild.showInput = true
      newChild.remove = true
      if (val) {
        val.children.push({
          label: '',
          children: [],
          parentId: val.id,
          showInput: true,
          remove: true,
          level: val.level + 1
        })
      } else {
        this.deptOptions.unshift(newChild)
      }
      console.log(val, this.deptOptions)
    },
    // 确定添加树节点
    sureNode(node, data) {
      this.appendState = false
      if (data.label) {
        if (data?.id) {
          updateCatalogue({
            name: data.label,
            parentId: data.parentId,
            id: data.id
          }).then((res) => {
            this.$message.success('更新成功')
            this.getTreeselect()
            data.showInput = false
            data.remove = true
          })
        } else {
          createCatalogue({ name: data.label, parentId: data.parentId }).then(
            (res) => {
              this.$message.success('新增成功')
              this.getTreeselect()
              data.showInput = false
              data.remove = true
            }
          )
        }
      } else {
        this.$message.error('名称不能为空')
      }
    },
    // 重命名node
    editNode(node, data) {
      data.remove = false
      data.showInput = true
      data.oldItemLabel = data.label
    },
    // 取消修改树节点
    remove(node, data) {
      console.log(node, data)
      const parent = node.parent
      const children = parent.data.children || parent.data
      const index = children.findIndex(d => d.id === data.id)
      if (data.id) {
        data.remove = true
        data.showInput = false
        data.label = data.oldItemLabel
      } else {
        children.splice(index, 1)
      }
    },
    //  删除节点
    delNode(node, data) {
      this.$modal
        .confirm('是否确认删除所选项？')
        .then(function() {
          return deleteByIdCatalogue({ id: data.id })
        }).then((res) => {
          this.$message.success('删除成功')
          this.getTreeselect()
        })
    },
    // 获取所有字典名称
    handleQuery(val) {
      this.queryParams.current = 1
      this.queryParams.name = val?.name
      this.getListData()
    },

    /** 查询列表 */
    getListData() {
      this.loading = true
      pageList(this.queryParams).then((res) => {
        this.total = res.total
        this.tableData = res.list
        this.loading = false
      })
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
    },
    /** 查询目录数据 */
    getTreeselect() {
      return new Promise((resolve, reject) => {
        listTreeCatalogue().then((res) => {
          this.deptOptions = res.map((item) => {
            return {
              children: this.treeChild(item.children),
              label: item.name,
              id: item.id,
              level: item.level,
              parentId: item.parentId,
              showInput: false,
              remove: true
            }
          })
          resolve(this.deptOptions)
        })
      })
    },
    // 递归数据
    treeChild(item) {
      if (item) {
        return item.map((i) => {
          return {
            children: this.treeChild(i.children),
            label: i.name,
            level: i.level,
            id: i.id,
            parentId: i.parentId,
            showInput: false,
            remove: true
          }
        })
      } else return
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      return new Promise((resolve, reject) => {
        this.isHightlight = true
        this.queryParams.catalogueId = data.id
        resolve(this.queryParams)
      }).then(() => {
        this.getListData()
      })
    },
    // 右侧新增完成
    handleSubmit() {
      this.getListData()
      this.getTreeselect()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$refs.addDrawerRef.handleShow('add')
      this.title = '添加'
    },
    // 删除
    handleDel() {
      const _this = this
      this.$modal
        .confirm('是否确认删除所选数据项？')
        .then(function() {
          return deleteServiceDef(_this.ids)
        })
        .then(() => {
          this.$modal.msgSuccess('删除成功')
          this.getListData()
        })
        .catch((error) => {})
    },
    //  编辑
    handleEdit(row) {
      this.$refs.addDrawerRef.handleShow('edit', row)
      this.title = '编辑'
    },
    //  设定优先级
    handleSet(row) {
      console.log(row)
      this.$router.push({
        path: window.prefix + '/bpmn/service/priority',
        query: {
          id: row.id,
          description: row.description,
          flowName: row.flowName
        }
      })
    },

    //  类型转义
    /*   setTemplateType(type) {
      let typeLabel = "";
      for (let i = 0; i < this.deptOptions.length; i++) {
        if (this.deptOptions[i].itemVale === type) {
          typeLabel = this.deptOptions[i].itemLabel;
          break;
        }
      }
      return typeLabel;
    }, */
    //  修改状态
    handleChangeEnable(row) {
      updateEnable({ id: row.id, enable: row.enable })
        .then((res) => {
          this.$message.success('修改成功')
          this.getListData()
        })
        .catch((error) => {
          this.getListData()
        })
    },
    //  导入
    handleImport() {
      this.$refs.importDialogRef.open = true
    },
    //  导出
    handleExport() {
      const ids = this.ids.join(',')
      gDownload('/ticket-api/serviceDef/export', { ids: ids }, `服务列表数据.xlsx`)
    },
    //  是否可删除导出
    selectFn(row, index) {
      return row.isSystem == false
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-tree-node__expand-icon.is-leaf{
  // display:none;
}
::v-deep .el-icon-circle-plus {
  font-size: 16px !important;
}
.app-container {
  padding: 0;
}
.user {
  padding: 20px;
  flex: 1;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow:auto !important;
}
.full-row {
  width: 100%;
  display: flex;
  margin: 0 !important;
  height: 100%;

  .full-height {
    height: 100%;
    display: flex;
    width: 340px !important;
    flex-direction: column;
    border-right: 1px solid rgba(0, 0, 0, 0.08);

    .head-container {
      margin-top: 10px;
      .title {
        background: #f8f8f8;
        font-size: 16px;
        padding: 5px 5px !important;
        .tit-left {
          flex: 1;
          span {
            cursor: pointer;
            margin-left: 10px;
          }
        }
      }
    }
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width:100%;
  }
}
.innerput::v-deep input {
  width: 150px;
  font-size: 14px;
  padding: 0 5px;
}
</style>
<style lang="scss">
.dictMapping {
  width: 100%;
  height: 100%;
  .el-tree {
    margin-top: 10px;
    font-size: 14px;
  }
}
</style>
